package com.ropeok.dao.impl;

import com.ropeok.dao.RoleDao;
import com.ropeok.entity.Role;
import com.ropeok.entity.permissions;
import com.ropeok.util.c3p0Util;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;


public class RoleDaoImpl implements RoleDao {


    Connection connection= c3p0Util.getConnection();
    @Override
    public List<Role> FindAll() {
        List<Role> list=new ArrayList<>();
        try{
            PreparedStatement preparedStatement= connection.prepareStatement("select *from t_permissions");
            ResultSet resultSet = preparedStatement.executeQuery();
            Role role;
            while (resultSet.next()){
                role=new Role(); //实例化对象，避免创建的都是同一对象
                role.setRoleid(resultSet.getInt("roeleid"));
                role.setRolename(resultSet.getString("rolename"));
                list.add(role);
            }
        }catch (SQLException e){
            e.printStackTrace();
        }
        return list;
    }

    @Override
    public void Save(Role role) {
        try{
            PreparedStatement preparedStatement=connection.prepareStatement("insert into t_role values (?,?)");
            preparedStatement.setInt(1,role.getRoleid());
            preparedStatement.setString(2,role.getRolename());
            preparedStatement.executeUpdate();
        }catch (SQLException e){
            e.printStackTrace();
        }

    }


    @Override
    public void UpdateRole(Role role) {

    }

    @Override
    public void DelRole(int id) {
        try{
            PreparedStatement preparedStatement=connection.prepareStatement("delete from t_permissions where roleid=?");
            preparedStatement.setInt(1,id);
            preparedStatement.executeUpdate();
        }catch (SQLException e){
            e.printStackTrace();
        }

    }

    @Override
    public List<Role> findByUserid(Integer id) {
        List<Role> list=new ArrayList<>();
        try{
            PreparedStatement pre= connection.prepareStatement("select roleid,rolename from t_role tr ,user_role ur where ur.role_id =tr.roleid and ur.user_id =?");
            pre.setInt(1,id);
            Role role;
            ResultSet rs = pre.executeQuery();
            while (rs.next()){
                role=new Role(); //实例化对象，避免创建的都是同一对象
                role.setRoleid(rs.getInt("roleid"));
                role.setRolename(rs.getString("rolename"));
                list.add(role);
            }
        }catch (SQLException e){
            e.printStackTrace();
        }
        return list;
    }
}
